package MyFramePro.MybatisPlus;

import MyFramePro.Domain.Entity.LoginUser;
import MyFramePro.Utils.SecurityUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import net.sf.cglib.core.Local;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 这里是 mybatisPlus 相关属性自动填充配置类
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 进行插入操作的时候进行自动属性填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        Long userId = null;

//        if(!(SecurityUtils.getAuthentication().getPrincipal() instanceof LoginUser)){
//            userId = -1L;
//        }else{
//            userId = SecurityUtils.getUserId();
//        }

        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            userId = -1L; //表示是自己创建
        }

        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("createBy",userId , metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
    }

    /**
     * 进行修改操作的时候进行自动属性填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        if(!Objects.isNull(SecurityUtils.getUserId())) {
            this.setFieldValByName("updateTime", new Date(), metaObject);
            this.setFieldValByName(" ", SecurityUtils.getUserId(), metaObject);
        }
    }

}